package com.qs.eggs.view.fragment;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.qs.eggs.R;
import com.qs.eggs.account.LoginActivity;
import com.qs.eggs.adapter.BaseAdapter;
import com.qs.eggs.adapter.CartAdapter;
import com.qs.eggs.api.HttpApi;
import com.qs.eggs.base.fragment.BaseFragment;
import com.qs.eggs.bean.ShoppingCart;
import com.qs.eggs.refresh.adapter.BaseRecyclerAdapter;
import com.qs.eggs.refresh.widget.RecyclerRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

public class CartFragment extends BaseFragment implements View.OnClickListener,RecyclerRefreshLayout.SuperRefreshLayoutListener{

    private RecyclerView recyclerView;
    private CartAdapter cartAdapter;
    private TextView mEdit;
    private TextView mTextTotal;
    private CheckBox checkBoxAll;
    private TextView mDel;
    protected RecyclerRefreshLayout mRefreshLayout;
    protected boolean isRefreshing;

    private LinearLayout toSubbmit,viewKong,mBottomTitle;
    public static final int ACTION_EDIT=1;
    public static final int ACTION_CAMPLATE=2;
    private static ArrayList<HashMap<String,String>> delList;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_cart;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mRefreshLayout = (RecyclerRefreshLayout) root.findViewById(R.id.refreshLayout);

        recyclerView=findView(R.id.rv_pro);
        mTextTotal=findView(R.id.txt_total);
        checkBoxAll=findView(R.id.checkbox_all);
        toSubbmit=findView(R.id.lly_tosubmit);
        viewKong=findView(R.id.lly_kong);
        mBottomTitle=findView(R.id.bottom_title);
        mDel=findView(R.id.tv_del);
        mEdit=findView(R.id.tv_edit);
        mEdit.setOnClickListener(this);
        mEdit.setTag(ACTION_EDIT);

        mDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a=0;
                for (int i=0;i<recyclerView.getChildCount();i++ ){
                    View view = recyclerView.getChildAt(i);
                    CheckBox cbitem = (CheckBox)view.findViewById(
                            R.id.checkbox);
                    if(cbitem.isChecked()){
                        a=1;
                    }
                }
                if(a==0){
                    Toast.makeText(getContext(),"未选中商品",Toast.LENGTH_SHORT).show();
                }else {
                    delCarGoods();
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        mRefreshLayout.setSuperRefreshLayoutListener(this);
        mRefreshLayout.setColorSchemeResources(
                R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        requestData();

    }

    @Override
    public void onClick(View v) {
        int action=(int)v.getTag();
        switch (action){
            case ACTION_EDIT:
                if(cartAdapter!=null)
                    showDelControl();

                break;
            case ACTION_CAMPLATE:
                if(cartAdapter!=null)
                    hideDelControl();
                break;
        }
    }

    private void showDelControl(){
        mEdit.setText("完成");
        mTextTotal.setVisibility(View.GONE);
        toSubbmit.setVisibility(View.GONE);
        mDel.setVisibility(View.VISIBLE);
        mEdit.setTag(ACTION_CAMPLATE);

        cartAdapter.checkAll_None(false);
        checkBoxAll.setChecked(false);

    }

    private void  hideDelControl(){

        mTextTotal.setVisibility(View.VISIBLE);
        toSubbmit.setVisibility(View.VISIBLE);
        mDel.setVisibility(View.GONE);
        mEdit.setText("编辑");
        mEdit.setTag(ACTION_EDIT);

        cartAdapter.checkAll_None(true);
        cartAdapter.showTotalPrice();

        checkBoxAll.setChecked(true);
    }

    /**
     * 删除购物车中选中的商品
     */
    private void delCarGoods(){
        String ids="";
        for (int j=0;j<recyclerView.getChildCount();j++){
            View view=recyclerView.getChildAt(j);
            CheckBox cb=(CheckBox)view.findViewById(R.id.checkbox);
            if (cb.isChecked()){
                ids=ids+delList.get(j).get("id")+",";
//                if(!list.isEmpty()){
//                    ids=ids+delList.get(j).get("id")+",";
//                }else {
                    cartAdapter.delCart();
//                    Toast.makeText(getContext(),"删除成功",Toast.LENGTH_SHORT).show();
//                }

            }

        }
        if(ids.length()!=0){
            ids=ids.substring(0,ids.length()-1);
        }else {
            ids="";
        }

        HttpApi.delCartPro(ids, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                if(!cartAdapter.isNull()){
                    viewKong.setVisibility(View.VISIBLE);
                    mBottomTitle.setVisibility(View.GONE);
                }else {
                    viewKong.setVisibility(View.GONE);
                    mBottomTitle.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
            }
        });
    }

    /**
     * 获取购物车列表
     */
    private void requestData(){
        HttpApi.cheakIsLogin(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if(s.equals("\"true\"")){
                    HttpApi.getCartPro(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            mRefreshLayout.onComplete();

                            delList=new ArrayList<HashMap<String, String>>();
                            Type type = new TypeToken<ArrayList<ShoppingCart>>() {
                            }.getType();

                            GsonBuilder gsonBuilder = new GsonBuilder();
                            ArrayList<ShoppingCart> resultBean = gsonBuilder.create().fromJson(s, type);

                            cartAdapter = new CartAdapter(getContext(), resultBean,checkBoxAll,mTextTotal);
                            cartAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
//                        Intent intent=new Intent(getContext(), ProDetailActivity.class);
//                        startActivity(intent);
                                }
                            });
                            recyclerView.setAdapter(cartAdapter);
                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                            recyclerView.setItemAnimator(new DefaultItemAnimator());

                            if(!cartAdapter.isNull()){
                                viewKong.setVisibility(View.VISIBLE);
                                mBottomTitle.setVisibility(View.GONE);
                            }else {
                                viewKong.setVisibility(View.GONE);
                                mBottomTitle.setVisibility(View.VISIBLE);

                            }

                            for(int i=0;i<resultBean.size();i++){
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("id",resultBean.get(i).getId()+"");
                                delList.add(map);
                            }
                        }
                    });
                }else {
                    LoginActivity.show(getContext());
                }

            }
        });
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        requestData();
    }

    @Override
    public void onLoadMore() {
      //  mAdapter.setState(isRefreshing ? BaseRecyclerAdapter.STATE_HIDE : BaseRecyclerAdapter.STATE_LOADING, true);
        requestData();
    }
}
